package trb.complexshield.bool.distance;

import no.hrp.hvrc.utils.j3d.BBox;
import no.hrp.hvrc.utils.j3d.Mat4;
import no.hrp.hvrc.utils.j3d.Vec3;
import trb.complexshield.bool.IntersectableBox;

public class BoxDistance implements DistanceProducer {

    private IntersectableBox box;
    Mat4 worldToLocal;
    float[] minMax;

    public BoxDistance(IntersectableBox box) {
        this.box = box;
        worldToLocal = box.getWorldToLocal();
        minMax = box.getMinMax();
    }

    @Override
    public float getDistance(Vec3 pos) {
        Vec3 local = worldToLocal.transformAsPoint(new Vec3(pos));
        BBox bbox = new BBox(minMax);
        local.sub(bbox.getCenter());
        Vec3 size = bbox.getSize().scale_(0.5f);
        Vec3 d = new Vec3(local).absolute_().sub_(size);
        return Math.min(Math.max(d.x, Math.max(d.y, d.z)), 0f) + new Vec3(d).clampMin_(0f).length();
    }
}
